package com.echat.ebluetooth;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.echat.ebluetooth.adapter.BeaconAdapter;
import com.echat.ebluetooth.bean.Beacon;
import com.echat.ebluetooth.service.BluetoothSearchService;
import com.echat.ebluetooth.util.PreferencesUtils;
import com.inuker.bluetooth.library.utils.BluetoothUtils;

import java.util.ArrayList;
import java.util.List;

import static com.echat.ebluetooth.constant.Constants.ACTION_REFRESH_UI;
import static com.echat.ebluetooth.constant.Constants.KEY_SAVE;
import static com.echat.ebluetooth.constant.Constants.SEARCH_RESULT;

public class MainActivity extends AppCompatActivity {

    public static final int LOCATION_CODE = 1;

    private BeaconAdapter mBeaconAdapter;
    private List<Beacon> mBeaconList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_REFRESH_UI);
        registerReceiver(refreshUiReceiver, intentFilter);

        boolean isSave = (boolean) PreferencesUtils.get(this, KEY_SAVE, false);
        if(!isSave){
            startActivity(new Intent(MainActivity.this, SettingActivity.class));
            return;
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_CODE);
            return;
        }
        startBluetoothService();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(refreshUiReceiver);
        stopBluetoothService();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.bluetooth_switch:
                if(BluetoothUtils.isBluetoothEnabled()){
                    BluetoothUtils.closeBluetooth();
                } else {
                    BluetoothUtils.openBluetooth();
                }
                break;
            case R.id.setting:
                startActivity(new Intent(MainActivity.this, SettingActivity.class));
                break;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == LOCATION_CODE){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                startBluetoothService();
            } else {
                Toast.makeText(this, "程序需要定位权限才能运行，请授予定位权限！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(llm);
        mBeaconList = new ArrayList<>();
        mBeaconAdapter = new BeaconAdapter(mBeaconList);
        recyclerView.setAdapter(mBeaconAdapter);
    }

    private void startBluetoothService (){
        startService(new Intent(MainActivity.this, BluetoothSearchService.class));
    }

    private void stopBluetoothService(){
        stopService(new Intent(MainActivity.this, BluetoothSearchService.class));
    }

    BroadcastReceiver refreshUiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle data = intent.getExtras();
            if(data != null){
                ArrayList<Beacon> beacons = data.getParcelableArrayList(SEARCH_RESULT);
                if(beacons != null && beacons.size() > 0){
                    mBeaconList.clear();
                    mBeaconList.addAll(beacons);
                    mBeaconAdapter.notifyDataSetChanged();
                }
            }
        }
    };

}
